const sourceMap = require('source-map');
// const SourceMapConsumer = sourceMap.SourceMapConsumer;
/**
* 转换
* @param {number} line
* @param {column} column
* @return {promise} result
*/
// TODO:异步readFile; 减少实例化 consumer
async function mapSourceInfo(generatedJsonData, generatedLine, generatedColumn) {
	try {
		// const buffer = fs.readFileSync(file) //
		// const rawSourceMapJsonData = JSON.parse(buffer.toString());
		const consumer = await new sourceMap.SourceMapConsumer(generatedJsonData);
		const {
			source, line, column, name,
		} = consumer.originalPositionFor({ line: parseInt(generatedLine, 10), column: parseInt(generatedColumn, 10) });
		const index = consumer._sources._set.get(source);
		const sourceCode = consumer.sourcesContent[index];
		const lines = sourceCode.split('\n');
		const code = lines[line - 1];
		consumer.destroy();
		return {
			file: source,
			line,
			column,
			code,
		};
	} catch (error) {
		throw new Error(error.message);
	}
}

module.exports = mapSourceInfo;
